package org.lionsoul.websnail.store;

import redis.clients.jedis.Jedis;

import java.util.HashMap;

/**
 * Persistent visited implementation base on redis
 *
 * @author yangjian
 **/
public class RedisVisited implements Visited
{

    private static final String MAP_VAL = "1";
    private final Jedis jedis;
    private final String key;

    /**
     * @param host     redis server host
     * @param port     redis server port
     * @param database redis database index
     * @param key      key for map in redis
     */
    public RedisVisited(String host, int port, int database, String key)
    {
        jedis = new Jedis(host, port);
        if (database > 0) { // 指定数据库
            jedis.select(database);
        }
        this.key = key;
        if (!jedis.exists(key)) {
            HashMap<String, String> map = new HashMap<>(2000, 0.8f);
            map.put("initialize", "WebSnail");
            this.jedis.hmset(key, map);
        }
    }

    @Override
    public synchronized boolean add(String url)
    {
        jedis.hset(key, url, MAP_VAL);
        return true;
    }

    @Override
    public synchronized boolean add(String[] urls)
    {
        for (String url : urls) {
            jedis.hset(key, url, MAP_VAL);
        }
        return true;
    }

    @Override
    public synchronized boolean remove(String url)
    {
        jedis.hdel(key, url);
        return true;
    }

    @Override
    public synchronized void clear()
    {
        jedis.del(key);
    }

    @Override
    public synchronized boolean contains(String url)
    {
        return jedis.hexists(key, url);
    }

    @Override
    public synchronized int size()
    {
        return (int) jedis.hlen(key);
    }

    @Override
    public synchronized void close()
    {
        jedis.close();
    }
}
